﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace WebApplicationFiller
{
    class ToolStripSpringTextBox : ToolStripTextBox
    {
        /// <summary>
        /// Overides GetPreferredSize method to allow spring capabilites on a ToolStrip
        /// </summary>
        /// <param name="constrainingSize"></param>
        /// <returns></returns>
        public override Size GetPreferredSize(Size constrainingSize)
        {
            if (IsOnOverflow || Owner.Orientation == Orientation.Vertical)
            {
                return DefaultSize;
            }

            //Gets the total availale width 
            int width = Owner.DisplayRectangle.Width;

            // Sets overflow width of button
            if (Owner.OverflowButton.Visible)
            {
                width = width - Owner.OverflowButton.Width - 
                    Owner.OverflowButton.Margin.Horizontal;
            }

            // Maintains control count of woning toolstrip
            int springBoxCount = 0;

            foreach (ToolStripItem item in Owner.Items)
            {
                //Ignore items on overflow menu
                if (item.IsOnOverflow) continue;

                if (item is ToolStripSpringTextBox)
                {
                    // Add to item count
                    // subtract the margin width from the total available width
                    springBoxCount++;
                    width -= item.Margin.Horizontal;
                }
                else
                {
                    // For other itmes, subtract teh full width from the available width
                    width = width - item.Width - item.Margin.Horizontal;
                }
            }

            //If there are multiple ToolStripSpringTextBox items in the owning ToolStrip
            //Divide the total available width between them
            if (springBoxCount > 1) 
                width /= springBoxCount;

            // If the available width is less than the default width, use the 
            // default width, forcing one or more items onto the overflow menu. 
            if (width < DefaultSize.Width) 
                width = DefaultSize.Width;

            // Get preferred size from the base class, but change the width to 
            // the calculated width
            Size size = base.GetPreferredSize(constrainingSize);
            size.Width = width;
            return size;
        }
    }
}
